package com.xfhy.skin.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;

import com.tools.R;

import support.SkinManager;
import support.widget.SkinCompatCheckBox;

/**
 * Created by xfhy on 2018/7/23 14:23
 * Description : 可以换肤的CheckBox  支持shape换肤
 */
public class SelectorCheckBox extends SkinCompatCheckBox {

    /**
     * 选中颜色的资源id
     */
    private int mCheckedBgColorResId;
    /**
     * 正常颜色的资源id
     */
    private int mNormalBgColorResId;

    public SelectorCheckBox(Context context) {
        this(context, null);
    }

    public SelectorCheckBox(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.checkboxStyle);
    }

    public SelectorCheckBox(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        readCustomAttribute(context, attrs);
        skinChange();
    }

    private void readCustomAttribute(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SelectorCheckBox);
        mCheckedBgColorResId = typedArray.getResourceId(R.styleable
                .SelectorCheckBox_checkedSelectorCheckBoxBGColor, R.color.main_theme_color);
        mNormalBgColorResId = typedArray.getResourceId(R.styleable
                .SelectorCheckBox_normalSelectorCheckBoxBGColor, R.color.color_f0f0f0);
        typedArray.recycle();
    }

    public void setCheckedBgColorResId(int checkedBgColorResId) {
        mCheckedBgColorResId = checkedBgColorResId;
    }

    public void setNormalBgColorResId(int normalBgColorResId) {
        mNormalBgColorResId = normalBgColorResId;
    }

    private void skinChange() {
        Drawable drawable = getBackground();
        if (drawable instanceof GradientDrawable) {
            GradientDrawable gradientDrawable = (GradientDrawable) drawable;
            if (isChecked()) {
                gradientDrawable.setColor(SkinManager.getColorArgbByContext(getContext(), mCheckedBgColorResId));
            } else {
                gradientDrawable.setColor(SkinManager.getColorArgbByContext(getContext(), mNormalBgColorResId));
            }
        }
    }

    @Override
    public void applySkin() {
        if (isEnabled()) {
            super.applySkin();
            skinChange();
        }
    }

    @Override
    public void setChecked(boolean checked) {
        super.setChecked(checked);
        skinChange();
    }
}
